package com.fruit.service.user.impl;


import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import com.fruit.mapper.user.UserMapper;
import com.fruit.pojo.address.Address;
import com.fruit.pojo.sms.SmsCodeValidate;
import com.fruit.pojo.sys.SysConfig;
import com.fruit.pojo.user.MyFruitTree;
import com.fruit.pojo.user.UserAccount;
import com.fruit.pojo.user.UserInfo;
import com.fruit.pojo.user.UserLogin;
import com.fruit.service.sms.SmsCodeManager;
import com.fruit.service.sys.SysManager;
import com.fruit.service.user.UserManager;
import com.fruit.util.CustomUtil;
import com.fruit.util.DateUtil;
import com.fruit.util.ResultInfo;
import com.fruit.util.ResultUtil;


/** 用户业务逻辑类
 * 修改时间：2016.07.14
 */
@Service("userService")
public class UserService implements UserManager{

	@Autowired
	private UserMapper userMapper;
	
	@Autowired
	private SmsCodeManager smsCodeService;
	
	@Autowired
	private SysManager sysService;
	
	@Value("${app.key}")
	private String key;

	@Override
	public UserLogin getUserLoginByToken(Map<String, Object> params) {
		return userMapper.getUserLoginByToken(params);
	}

	@Override
	public UserInfo getUser(int userId) {
		UserInfo user= userMapper.getUserById(userId);
		if(user != null){
			if(user.getSex() != null){
				if("00".equals(user.getSex())){
					user.setSex("女");
				}else if("01".equals(user.getSex())){
					user.setSex("男");
				}
			}
		}
		 return user;
	}

	@Override
	public UserInfo getUserInfoByLoginId(int loginId) {
		// TODO Auto-generated method stub
		return userMapper.getUserInfoByLoginId(loginId);
	}

	@Override
	public List<Address> getAddressList(int userId) {
		return userMapper.getAddressList(userId);
	}

	@Override
	public void updateAddStatus(Address addre) {
		userMapper.updateAddStatus(addre);
	}

	@Override
	public void saveAddress(Address address) {
		userMapper.saveAddress(address);
	}

	@Override
	public void updateAddress(Address address) {
		userMapper.updateAddress(address);
	}

	@Override
	public Address getAddressById(int addressId) {
		return userMapper.getAddressById(addressId);
	}

	@Override
	public void deleteAddress(int addressId) {
		userMapper.deleteAddress(addressId);
	}

	@Override
	public void updateUserHeadImage(UserInfo user) {
		userMapper.updateUserHeadImage(user);
	}

	@Override
	public void updateUserMess(UserInfo user) {
		if (user.getPetName() != null && user.getPetName() != "") {
            userMapper.updateUserPetName(user);
            return;
        }
        if (user.getSex() != null && user.getSex() != "") {
            userMapper.updateUserSex(user);
        }
	}
	
	@Override
	public Map<String, Object> updateToLogin(UserLogin ul) {
		Map<String, Object> resMap = new HashMap<String,Object>();
		try{
		//验证码是否正确
		String msg = smsCodeService.getValidateCode(ul.getPhone(), ul.getSmsCode(), "login");
		if(StringUtils.equals(msg, "expire")){
			resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "code_expire", "验证码已失效!"));
			return resMap;
		}else if(!StringUtils.equals(msg, "ok")){
			resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "code_error", "验证码有误!"));
			return resMap;
		}	
		
		//验证用户是否存在
		UserLogin userLogin = userMapper.getUserLoginByPhone(ul);
		if(userLogin != null){
			UserInfo userInfo = userMapper.getUserInfoByLoginId(userLogin.getId());
			if (!"01".equals(userInfo.getState())) {
				msg = "该用户已经被禁用，请联系管理员";
				resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "error", msg));
				return resMap;
			}
			
			ul.setId(userLogin.getId());
			//生成用户令牌
			String token = CustomUtil.makeUserToken(ul.getId(), key);
			userLogin.setToken(token);
			SysConfig sc = sysService.getSysConfigList().get(0);
			long tokenLoseTime = System.currentTimeMillis() + sc.getTokenTime();
			userLogin.setTokenLoseTime(tokenLoseTime);
			int num = updateUserLoginToken(userLogin);
			if(num == 0){
				resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "login_faile", "登录失败!"));
				return resMap;
			}
			resMap.put("token", token);
		}else{
			String token = CustomUtil.makeUserToken(ul.getId(), key);
			ul.setToken(token);
			SysConfig sc = sysService.getSysConfigList().get(0);
			long tokenLoseTime = System.currentTimeMillis() + sc.getTokenTime();
			ul.setTokenLoseTime(tokenLoseTime);
			userMapper.saveUserLogin(ul);
			UserInfo user = new UserInfo();
			user.setCodePre(DateUtil.getYear());
			user.setCodeSuf(CustomUtil.buildRandom(3) + "");
			user.setLoginId(ul.getId());
			user.setPhone(ul.getPhone());
			String petName = CustomUtil.subPhone(user.getPhone());
			user.setPetName(petName);
			userMapper.saveUserInfo(user);
			UserAccount account = new UserAccount();
			account.setUserId(user.getId());
			account.setLoginId(ul.getId());
			account.setBalance(new BigDecimal(0));
			account.setPoints(new BigDecimal(0));
			userMapper.saveUserAccount(account);
			resMap.put("token", token);
		}
		//修改短信码状态
		SmsCodeValidate validate = new SmsCodeValidate();
		validate.setCode(ul.getSmsCode());
		validate.setPhone(ul.getPhone());
		validate.setTypes("login");
		validate.setIsUse("01");
		int num = smsCodeService.upudateIsSue(validate);
		if(num == 0){
			resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "code_expire", "验证码已失效!"));
			return resMap;
		}
		UserInfo userInfo = userMapper.getUserInfoByLoginId(ul.getId());
		resMap.put("userInfo", userInfo);
		resMap.put("result", ResultUtil.initResult(ResultInfo.SUCCESS, "OK", "登录成功"));
		return resMap;
		}catch(Exception e){
			e.printStackTrace();
			resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "exception", "系统异常!", null, ResultInfo.ROLLBACK));
			return resMap;
		}finally{
			ResultInfo ri = (ResultInfo)resMap.get("result");
			if(ResultInfo.ROLLBACK.equals(ri.getIsRollBack())){
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			}
		}
	}

	@Override
	public int updateUserLoginToken(UserLogin ul) {
		return userMapper.updateUserLoginToken(ul);
	}

	@Override
	public UserLogin getUserLoginByPhone(UserLogin ul) {
		return userMapper.getUserLoginByPhone(ul);
	}

	@Override
	public List<MyFruitTree> getMyFruitTreeList(Map<String, Object> parame) {
		List<MyFruitTree> mf=new ArrayList<MyFruitTree>();
		mf= userMapper.getMyFruitTreeList(parame);
		if(mf.size()>0){
			for (MyFruitTree mft : mf) {
				if("00".equals(mft.getFruitTreeState())){
					mft.setFruitTreeState("种子");
				}else if("01".equals(mft.getFruitTreeState())){
					mft.setFruitTreeState("树苗");
				}else if("02".equals(mft.getFruitTreeState())){
					mft.setFruitTreeState("果树");
				}
				
			}
		}
		return mf;
	}
	
	


	
}
